<template>
  <div>
    <!--填写商品信息-->
    <el-form :model="product"  ref="ruleForm" label-width="100px">
              <el-form-item label="商品分类" prop="catalogId">
                <div class="block">
                  <el-cascader v-model="selectedCatalogIds" :options="regionList"
                               :props="{'value':'catId','label':'name','children':'chiledList'}"
                               @change="handleChange"></el-cascader>
                </div>
              </el-form-item>
              <el-form-item label="商品名称" prop="spuName">
                <el-input v-model="product.spuEntity.spuName"/>
              </el-form-item>
              <el-form-item label="副标题" prop="skuSubtitle">
                <el-input v-model="product.skuSubtitle"/>
              </el-form-item>
              <el-form-item label="商品品牌" prop="brandId">
                <el-select v-model="product.spuEntity.brandId" placeholder="请选择">
                  <el-option
                    v-for="item in brandList"
                    :key="item.brandId"
                    :label="item.name"
                    :value="item.brandId">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="商品介绍" prop="spuDescription">
                <el-input type="textarea" v-model="product.spuEntity.spuDescription"/>
              </el-form-item>
              <el-form-item label="商品售价" prop="price">
                <el-input v-model="product.price"/>
              </el-form-item>
              <el-form-item label="sku图片信息" prop="image">
                <image-upload v-model="product.image"></image-upload>
              </el-form-item>
              <el-form-item label="商品介绍" prop="descipt">
                <image-upload v-model="product.descipt"></image-upload>
              </el-form-item>
      <div id="app">
        <div>
          <div>
            <!-- 多规格 -->
            <div class="Multiple-specifications">
              <el-card title="多规格" style="border-radius: 10px;">
                <div style="display: flex;flex-flow: row wrap;">
                  <div v-for="(item, index) in product.attrVoList" :key="index">
                    <div label="规格名" :rules="{required: true, message: '请输入规格名',trigger: 'blur'}">
                      <div>
                        <el-input v-model="item.title" placeholder="规格名" style="width:200px"
                                  @change="makenewTabel(item, 'ruleName', '')" ></el-input>
                        <el-button @click="deletRow(index, item)">删除</el-button>
                      </div>
                    </div>
                    <div label="规格值" :rules="{required: true, message: '请输入规格值',trigger: 'blur'}">
                      <div v-for="(it, ix) in item.attrVosList" :key="ix" style="margin-left: 20px;">
                        <div>
                          <el-input v-model="it.value" placeholder="规格值" style="width:200px"
                                    @change="makenewTabel(item, 'value', it)" ></el-input>
                          <el-button @click="deletNum(ix, it, item, index)">删除</el-button>
                        </div>
                      </div>
                    </div>
                    <div @click="addSku(index)">+添加规格值</div>
                  </div>
                </div>
                <div @click="addOtherSku">+添加其他规格
                </div>
              </el-card>
            </div>
            <!-- 规格列表  -->
            <div class="Specification-list">
              <el-card title="规格列表" style="border-radius: 10px;">
                <el-table :data="duoTableData">
                  <el-table-column v-for="(val, key) in columns2" :key="key" :prop="val.dataIndex" :label="val.title">
                    <template slot-scope="scope">
                      <el-input placeholder="请输入" v-model="scope.row[val.dataIndex]" @blur="emitTableData"></el-input>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </div>
          </div>
        </div>
      </div>
    </el-form>
    <el-button @click="addProduct()">录入商品</el-button>
    <el-button @click="goto()">商品页</el-button>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）,
//例如：import 《组件名称》 from '《组件路径》,
  import axios from 'axios'
import {addProduct, brandList, categoryTree} from "../../../api/product/product/product";
  export default {
    //import引入的组件需要注入到对象中才能使用"
    components: {},
    props: {},
    data() {
      //这里存放数据"

      return {
        selectedCatalogIds:[],
        regionList:[],
        brandList:[],
        columns2:[],
        columns: [],
        duoTableData:[],
        product:{
          spuEntity: {
            spuName: "",
            spuDescription: "",
            catalogId: null,
            brandId: null,
            weight: null,
            skuTitle: "",

          },
          skuSubtitle: "",
          price: null,
          image: "",
          descipt: "",
          productAttrValue: "",
          attrVoList: [
            {
              title: "",
              oldTitle: "",
              attrVosList: [
                {
                  value: "",
                  oldValue: ""
                }
              ]
            }
          ],
          duoTableData: [
            {
              skuNo: "",
              weight: null,
              stock: null,
              price: ""
            }
          ]
        }
      };
    },
    //计算属性 类似于data概念",
    computed: {},
    //监控data中的数据变化",
    watch: {},
    //方法集合",
    methods: {
      goto(){
        this.$router.push({
          name: '商品页',
        })
      },
      //录入商品
      addProduct(){
        addProduct(this.product).then(res=>{
           this.$message.success("录入成功");
        })
      },
      // 重置表头
      /***
       * dragData的默认数据
       */
      initDrag() {
        this.product.attrVoList = this.product.attrVoList.length > 0 ? JSON.parse(JSON.stringify(this.product.attrVoList)) : [{
          title: '',
          oldTitle: '',
          attrVosList: [{
            value: '',
            oldValue:'',
          }]
        }]
        // 如果是新增取消确定 // 或者单规格，就要清空表头and 表格数据
        // 把old 也要清空
        this.duoTableData = []
      },
      /**
       * 得到列
       */
      resetColumns() {
        const rules = []
        for (var j = 0; j < this.product.attrVoList.length; j++) {
          const obj = {}
          obj.title = this.product.attrVoList[j].title
          obj.dataIndex = `newHead${obj.title}`
          rules.push(obj)
        }
        const columns = [...this.columns]
        columns.splice(1, 0, ...rules)
        this.columns2 = columns
      },
      async deletRow(index, item) {
        if (item.title) {
          const ret = await this.$confirm(`确定要删除 ${item.title} 规格？`)
          if (!ret) {
            return false
          }
        }
        this.product.attrVoList.splice(index, 1)
        this.tableData = this.product.attrVoList
        this.makenewTabel(item, 'deleteRule', index)
      },
      async deletNum(index, ix, item, iii) {
        if (item.attrVosList < 1) {
          this.$message.error('必须有一个规格值', 2)
          return false
        }
        if (ix.value) {
          let title = `确定要删除 ${item.title} 规格中的 ${ix.value}？`
          if (!item.title) {
            title = `确定要删除 ${ix.value} 规格值？`
          }
          const ret = await this.$confirm(title)
          if (!ret) {
            return false
          }
        }
        this.product.attrVoList[iii].attrVosList.splice(index, 1)
        this.makenewTabel(item, 'deleteRule', ix)
      },
      addSku(index) {
        this.product.attrVoList[index].attrVosList.push({
          value: '',
          oldValue: ''
        })
      },
      addOtherSku() {
        this.product.attrVoList.push({
          ruleName: '',
          attrValue: '',
          attrVosList: [{
            value: '',
            oldValue: ''
          }]
        })
      },
      /** 按规格得到笛卡尔乘积列表 handleList */
      getDecareList() {
        const ret = []
        if (this.product.attrVoList.length === 0) {
          return ret
        } else if (this.product.attrVoList.length === 1) {
          for (var m = 0; m < this.product.attrVoList[0].attrVosList.length; m++) {
            const e = {}
            e[`newHead${this.product.attrVoList[0].title}`] = this.product.attrVoList[0].attrVosList[m].value
            e['weightUnit'] = 'g'
            e['goodsStock'] = 0
            ret.push(e)
          }
          return ret
        }
        // 展开table中的数据
        const arr1 = this.product.attrVoList.map((item) => {
          const res = []
          item.attrVosList.forEach(v => {
            res.push({
              value: v.value,
              ruleName: item.title
            })
          })
          return res
        })
        // 构造笛卡尔乘积
        const r = arr1.reduce((col, row) => {
          const res = []
          col.forEach(c => {
            row.forEach(r => {
              const t = Array.isArray(c) ? [...c] : [`#${c.ruleName}#${c.value}`]
              t.push(`#${r.ruleName}#${r.value}`)
              res.push(t)
            })
          })
          return res
        })
        const pattern = new RegExp('#([^#]+)#(.*)')
        let match = []

        for (var i = 0; i < r.length; i++) {
          const e = {}
          for (var k = 0; k < r[i].length; k++) {
            match = pattern.exec(r[i][k])
            if (match) {
              e[`newHead${match[1]}`] = match[2]
              e['weightUnit'] = 'g'
              e['goodsStock'] = 0
            }
          }
          ret.push(e)
        }
        return ret
      },
      /*** 规格生成  */
      makenewTabel(item, type, value) {
        this.resetColumns()
        // 深拷贝一个值
        const copyListData = JSON.parse(`${JSON.stringify(this.duoTableData)}`)
        // 得到笛卡尔列
        const specificationListdata = this.getDecareList()
        const oldDataList = {}
        let speckey = []
        // 原值
        let key = ''
        let title = ''
        // 得到规格名用于data中旧的规格信息
        const ruleNames = this.product.attrVoList.map(table => {
          return `newHead${table.title}`
        })
        copyListData.forEach(data => {
          speckey = []
          this.product.attrVoList.forEach(table => {
            // 值变化
            title = `newHead${table.title}`
            key = data[title]
            if (!key) {
              if (type === 'value') {
                data[title] = value.value
                key = value.value
              }
            }
            if (type === 'value' && table === item && key === value.oldValue) {
              data[`newHead${table.title}`] = value.value
              key = value.value
            } else {
              if (type === 'ruleName' && table === item) {
                data[`newHead${table.title}`] = data[`newHead${table.oldTitle}`]
                key = data[`newHead${table.oldTitle}`]
              }
            }
            speckey.push(key)
          })
          // 删除原来的旧列原来的旧值
          Object.keys(data).forEach(key => {
            if (key.startsWith('newHead') && !ruleNames.includes(key)) {
              delete data[key]
            }
          })
          oldDataList[speckey.join('-')] = data
        })
        // 新值
        const temps = specificationListdata
        temps.forEach((data, index) => {
          speckey = []
          this.product.attrVoList.forEach(table => {
            speckey.push(data[`newHead${table.title}`])
          })
          key = speckey.join('-')
          if (oldDataList[key]) {
            temps[index] = oldDataList[key]
          }
        })
        this.duoTableData = temps
        if (type !== 'reset') {
          if (type === 'value') {
            value.oldValue = value.value
          } else {
            item.oldTitle = item.title
          }
        }
      },
      // 每次失去焦点后，把值emit
      emitTableData() {
        const emitData = {
          tableData: this.tableData,
          specificationListdata: this.specificationListdata
        }
      },
      //商品分类
      catalogList(){
        categoryTree().then(res=>{
          this.regionList = res.data
        })
      },
      //品牌列表
      getBrandList(){
        brandList().then(res=>{
          this.brandList = res.data
        })
      },
      handleChange(value) {
        this.product.spuEntity.catalogId = this.selectedCatalogIds[0]
      }
    },
    //生命周期 - 创建完成（可以访问当前this实例）",
    created() {
      this.catalogList();
      this.getBrandList();
      this.initDrag();
      this.columns = [
        {
          title: `售价(US$})`,
          dataIndex: 'salesPrice',
        },
        {
          title: `原价(US$})`,
          dataIndex: 'originalPrice',
        },
        {
          title: '重量',
          width: '180',
        },
        {
          title: '库存数量',
          dataIndex: 'goodsStock',
        },
        {
          title: 'SKU（货号）',
          dataIndex: 'skuNo',
        },
        {
          title: '条形码',
          dataIndex: 'barCode',
        },
        {
          title: '操作',
          dataIndex: 'action',
        }
      ]
      this.resetColumns()
    },
    //生命周期 - 挂载完成（可以访问DOM元素）",
    mounted() {

    },
    beforeCreate() {
    }, //生命周期 - 创建之前",
    beforeMount() {
    }, //生命周期 - 挂载之前",
    beforeUpdate() {
    }, //生命周期 - 更新之前",
    updated() {
    }, //生命周期 - 更新之后",
    beforeDestroy() {
    }, //生命周期 - 销毁之前",
    destroyed() {
    }, //生命周期 - 销毁完成",
    activated() {
    } //如果页面有keep-alive缓存功能，这个函数会触发",
  };
</script>
<style scoped>

</style>
